import { RequestConfig, history } from 'umi';
import { message } from 'antd';
import React from 'react';
import StoreContext from '@/context/storeContext'
import store from '@/models/store'
import { getToken } from './utils';

// 覆盖根组件
export function rootContainer(container: React.ReactNode) {
  return React.createElement(StoreContext.Provider, {value: store}, container);
}

// umi的导航守卫
export function onRouteChange() {
  console.log('history...', history);
  if (location.pathname.indexOf('/login') === -1){
    if (!getToken()){
      history.replace('/login?from='+encodeURIComponent(location.pathname));
    }
  }else{
    if (getToken()){
      history.replace('/');
    }
  }
}

// 配置网络请求
let hasError = false;

const baseURL = 'https://creationapi.shbwyz.com/api';
export const request: RequestConfig = {
  timeout: 10000,
  errorConfig: {},
  middlewares: [],
  requestInterceptors: [(url, options) => {
    // 添加登陆态
    let authorization = getToken();
    if (authorization){
      (options.headers as any)!.authorization = authorization;
    }
    url = url.indexOf('https')!==-1?url: `${baseURL+url}`;
    return {
      url,
      options: { ...options, interceptors: true },
    };
  }],
  responseInterceptors: [response => {
    const codeMaps:{[key:number]:string} = {
      400: '客户端请求错误',
      403: '请求不被允许',
      404: '接口不存在',
      500: '服务器内部错误',
      502: '网关错误。',
      503: '服务不可用，服务器暂时过载或维护。',
      504: '网关超时。',
    };
    if (Object.keys(codeMaps).indexOf(String(response.status)) !== -1){
      if (!hasError){
        hasError = true;
        message.error({
          content: codeMaps[response.status],
          onClose: ()=>{
            hasError = false;
          }
        });
        return response.body;
      }
    }else{
      return response;
    }
    return {};
  }],
};